package com.chen.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.chen.manager.service.SysUserService;
import com.chen.manager.mapper.SysUserMapper;
import com.chen.model.dto.system.LoginDto;
import com.chen.model.dto.system.SysUserDto;
import com.chen.model.entity.system.SysUser;
import com.chen.model.vo.common.ResultCodeEnum;
import com.chen.model.vo.system.LoginVo;
import com.chen.service.exception.MyException;
import com.chen.util.AuthContextUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author cgj
 * @date 2/6/25 2:15 PM
 */
@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Transactional(readOnly = true)
    @Override
    public LoginVo login(LoginDto loginDto) {
    //        先验证验证码是否正确
        String codeKey = loginDto.getCodeKey();  //获取redis存储的key
        String inputCaptcha = loginDto.getCaptcha();
        String redisCaptcha = redisTemplate.opsForValue().get("user:login:validateCode"+codeKey);      //从redis取出验证码
        if(StrUtil.isEmpty(redisCaptcha)||!StrUtil.equalsAnyIgnoreCase(inputCaptcha,redisCaptcha)){
            throw  new RuntimeException("验证码错误");
        }

        SysUser sysUser = sysUserMapper.selectSysUserByUserName(loginDto.getUserName());

        if(sysUser==null){
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
        }
        //        获取用户输入的明文
        String InputPassword = loginDto.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(InputPassword.getBytes());
        if(!md5Password.equals(sysUser.getPassword())){
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
        }
//        生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
//        存储到redis
        redisTemplate.opsForValue().set("user:login:"+token, JSON.toJSONString(sysUser),30, TimeUnit.MINUTES);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
//       删除验证码
        redisTemplate.delete("user:login:validateCode"+codeKey);


        return loginVo;
    }

    @Override
    public SysUser getUserINfo(String token) {
        String SysUserJson = redisTemplate.opsForValue().get("user:login:" + token);
        SysUser sysUser = JSON.parseObject(SysUserJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        if (!StrUtil.isEmpty(token)){

            redisTemplate.delete("user:login:" + token);
        }
    }
    @Transactional(readOnly = true)
    @Override
    public PageInfo<SysUser> selectSysUserByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> sysUserList = sysUserMapper.selectSysUserByPage(sysUserDto);
        return  new PageInfo<>(sysUserList);
    }


    @Override
    public void savaUser(SysUser sysUser) {
//        因为不是注册, 而是手动添加,需要判断用户是否存在
        SysUser querySysUser = sysUserMapper.selectSysUserByUserName(sysUser.getUserName());
        if(querySysUser!=null){ // 用户存在抛出异常
//            抛出这个异常,  程序不会继续往下走
            throw  new MyException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
//        进行密码加密
        String password = sysUser.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(md5Password);
//        设置状态为禁用, 因为用户还没有添加角色
        sysUser.setStatus(0);
//      完毕后新增
        sysUserMapper.insertSysUser(sysUser);

    }

    public static void main(String[] args) {

        String md5Password = DigestUtils.md5DigestAsHex("111111".getBytes(StandardCharsets.UTF_8));
        System.out.println(md5Password);
    }

    @Override
    public void editUser(SysUser sysUser) {
//        //防止用户把用户名改重复
//        SysUser querySysUser = sysUserMapper.selectSysUserByUserName(sysUser.getUserName());
//        if(querySysUser!=null){
//            //说明用户名已经存在, 直接退出即可
//            throw new MyException(ResultCodeEnum.USER_NAME_IS_EXISTS);
//        }
        sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public void deleteUserById(Integer id) {
        sysUserMapper.deleteUserById(id);
    }


}
